import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {
    private  Socket socket;
    private  String name;
    private  ObjectOutputStream oos;
    private  ObjectInputStream ois;

    public static void main(String[] args) {
        new ChatClient();
    }

    public ChatClient (){
        try {
            socket = new Socket("localhost", 9900);
            //提示用户输入姓名并处理用户在控制台输入的姓名
            Scanner sc = sendNameAndRecvEcho();
            new Thread() {
                @Override
                public void run() {
                    while (socket != null) {
                        try {
                            String msg = (String) ois.readObject();
                            System.out.println(msg);

                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();

            new Thread() {
                @Override
                public void run() {
                    while (socket != null) {
                        try {
                            Scanner sc = new Scanner(System.in);
                            String msg = sc.nextLine();
                            oos.writeObject(msg);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                    }.start();
            while (true) {
                String msg = sc.nextLine();
                oos.writeObject(msg);
                System.out.println(ois.readObject());

               
            }
        
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
    }

    private Scanner sendNameAndRecvEcho() throws IOException, ClassNotFoundException {
        System.out.println("请输入您的姓名:");
        //使用Scanner实现从控制台输入
        Scanner sc = new Scanner(System.in);
        name = sc.nextLine();

        //获得与服务器端通信的输出流对象，并向服务器端发送姓名
        OutputStream os = socket.getOutputStream();
        oos = new ObjectOutputStream(os);
        oos.writeObject(name);

        //接收服务器端的消息并在控制台输出
        InputStream is = socket.getInputStream();
        ois = new ObjectInputStream(is);
        System.out.println(ois.readObject());
        return sc;
    }

}

